package org.darkforest.fileServer.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
@RequestMapping("/file")
public class FileController {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(FileController.class);

    @RequestMapping("/uploadImage")
    public String uploadImage(HttpServletRequest request, HttpServletResponse response) {

        try {

            // 判断enctype属性是否为multipart/form-data
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (!isMultipart) {
                response.setCharacterEncoding("UTF-8");
                response.getWriter().println("上传内容不是有效的multipart/form-data类型.");
                System.out.println("上传内容不是有效的multipart/form-data类型.");
                return null;
            }

            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Parse the request
            List<FileItem> items = upload.parseRequest(request);
            System.out.println("items.size()=" + items.size());

            // 商品图片、员工照片
            String imageFlg = "goods";

            for (FileItem item : items ) {
                if (item.isFormField()) {
                    // 如果是普通表单字段
                    String name = item.getFieldName();
                    String value = item.getString();
                    // 文件类型设定参数
                    if ("imageFlg".equals(name)) {
                        imageFlg = value;
                    }
                    logger.info("-----name：" + name + "-----value：" + value);
                } else {
                    // 如果是文件字段
                    String fileName = item.getName();
                    logger.info("-----fileName：" + fileName);
                    //写入文件到当前服务器磁盘
                    String fileFullName = getFileFullName(fileName, imageFlg);
                    logger.info("保存的文件为：" + fileFullName);
                    File uploadedFile = new File(fileFullName);
                    item.write(uploadedFile);
                    // 删除临时文件
                    item.delete();
                }
            }

            response.setCharacterEncoding("UTF-8");
            response.getWriter().println("上传成功");
            return null;
        }  catch (IllegalStateException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     *  取得文件名称
     * @param filename
     * @return
     */
    private String getFileFullName(String filename, String imageFlg) {
        // 获取路径
        String dirPath = System.getProperty("catalina.home").concat(File.separator).concat("webapps");
        if ("goods".equals(imageFlg)) {
            dirPath = dirPath.concat(File.separator).concat("goodsImgs");
        } else {
            // imageFlg = "member_"+memberId
            if (imageFlg.startsWith("member_")) {
                String memberId = imageFlg.split("_")[1];
                dirPath = dirPath.concat(File.separator).concat("memberImgs");
                dirPath = dirPath.concat(File.separator).concat(memberId);
            }
        }

        File imagePath = new File(dirPath);
        if (!imagePath.exists()) {
            imagePath.mkdir();
        }

        System.out.println("imagePath=" + dirPath);

        String fileFullName = dirPath.concat(File.separator).concat(filename);

        return fileFullName;
    }

    /**
     *  测试用
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/upload/image")
    @ResponseBody
    public String uploadImageTest(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取路径
            String dirPath = System.getProperty("catalina.home").concat(File.separator).concat("webapps");
            dirPath = dirPath.concat(File.separator).concat("goodsImgs");
            File imagePath = new File(dirPath);
            if (!imagePath.exists()) {
                imagePath.mkdir();
            }

            System.out.println("imagePath=" + dirPath);

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartRequest.getFile("filePicture");
            String fileNameTmp = multipartFile.getOriginalFilename();
            if (fileNameTmp.contains(File.separator)) {
                fileNameTmp = fileNameTmp.substring(fileNameTmp.lastIndexOf(File.separator));
            }
            String randomUUID = UUID.randomUUID().toString();
            // 后缀变小写
            String suffix = fileNameTmp.substring(fileNameTmp.lastIndexOf(".") + 1).toLowerCase();
            String fileName = randomUUID + "." + suffix;
            File localFile = new File(dirPath + File.separator + fileName);
            if (multipartFile.getSize() > 10240000) {
                return "SizeError";
            }

            multipartFile.transferTo(localFile);

            System.out.println("localFile=" + localFile);
            System.out.println("fileName=" + fileName);

            return fileName;
        }  catch (IllegalStateException e) {
            e.printStackTrace();
            return "Error";
        } catch (IOException e) {
            e.printStackTrace();
            return "Error";
        } catch (Exception e) {
            e.printStackTrace();
            return "Error";
        }
    }
}
